package com.lft.examsys.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lft.examsys.entity.Paper;
import com.lft.examsys.entity.User;
import com.lft.examsys.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder encoder;

    public User findByName(String username) {
        return userMapper.findByUsername(username);
    }

    public User findById(Integer id) {
        return userMapper.selectById(id);
    }

    public boolean register(User user) {
        if (userMapper.findByUsername(user.getUsername()) != null) {
            return false;
        }
        user.setPassword(encoder.encode(user.getPassword()));
        return userMapper.register(user) > 0;
    }

    public List<Paper> getRecentPapers(Integer userId) {
        List<Paper> papers = userMapper.selectPapaersAllById(userId);
        return papers;
    }

    public Boolean update(User user) {
        return userMapper.updateUser(user);
    }

    public Page<User> getAllByPage(Integer page, Integer size) {
        page = page == null ? 1 : page;
        size = size == null ? 10 : size;
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("id");
        Page<User> res = new Page<>(page, size);
        userMapper.selectPage(res, wrapper);
        return res;
    }

    public void SetRole(Integer id, String role) {
        userMapper.setRole(id, role);
    }

    public void ban(Integer id, Boolean ban) {
        userMapper.ban(id,ban);
    }
}
